<template>
  <div class="index-container">
    <el-page-header class="detailheader" :icon="ArrowLeft" @back="goBack">
      <template #content>
        <ww-open-data :openid="data.reqUserid" type="userName" />
        代课申报
        <span v-if="data.status === 0" class="sp_status sp_status_0">
          未提交
        </span>
        <span v-if="data.status === 1" class="sp_status sp_status_1">
          审批中
        </span>
        <span v-if="data.status === 2" class="sp_status sp_status_2">
          已通过
        </span>
        <span v-if="data.status === 3" class="sp_status sp_status_3">
          已驳回
        </span>
        <span v-if="data.status === 4" class="sp_status sp_status_4">
          已取消
        </span>
      </template>
    </el-page-header>
    <div class="page__cont">
      <div class="row1">
        <div class="label">审批编号：</div>
        <div class="description">
          {{ data.thirdNo }}
        </div>
      </div>
      <div class="row1">
        <div class="label">申报人：</div>
        <div class="description">
          <ww-open-data :openid="data.reqUserid" type="userName" />
        </div>
      </div>
      <div class="row1">
        <div class="label">申请时间：</div>
        <div class="description">
          {{ parseTime(data.createtime) }}
        </div>
      </div>
      <div class="row1">
        <div class="label">事 由：</div>
        <div class="description">
          {{ data.comment }}
        </div>
      </div>
      <el-divider content-position="left">
        <span style="color: darkgrey">代课明细</span>
      </el-divider>
      <div v-for="(course, index) in data.courses" :key="index">
        <div class="row1">
          <div class="label">
            代课{{ data.courses.length > 1 ? index + 1 : '' }}：
          </div>
          <div class="description">
            <div>
              代课老师：
              <ww-open-data :openid="course.tarUserid" type="userName" />
            </div>
            <div>
              被代老师：
              <ww-open-data :openid="course.srcUserid" type="userName" />
            </div>
            <div>
              课程：
              {{ getCourseDesc(course) }}
            </div>
          </div>
        </div>
      </div>
      <el-divider content-position="left">
        <span style="color: darkgrey">审批流程</span>
      </el-divider>
      <div class="row1">
        <div class="label">审批人：</div>
        <div class="description">
          <ww-open-data :openid="data.auditUserid" type="userName" />
        </div>
      </div>
      <div class="row1">
        <div class="label">审核时间：</div>
        <div class="description">
          {{ data.status > 1 ? parseTime(data.audittime) : '' }}
        </div>
      </div>
      <div class="row1">
        <div class="label">审批状态：</div>
        <div class="description">
          <div v-if="data.status === 0" style="color: burlywood">未提交</div>
          <div v-if="data.status === 1" style="color: #4b95f3">审批中</div>
          <div v-if="data.status === 2" style="color: #1ebd43">已通过</div>
          <div v-if="data.status === 3" style="color: red">已驳回</div>
          <div v-if="data.status === 4" style="color: darkgray">已取消</div>
        </div>
      </div>
      <div class="row1">
        <div class="label">审批意见：</div>
        <div class="description">
          {{ data.auditNotes }}
        </div>
      </div>
      <div class="rowx">
        <el-button
          v-if="data.status < 2"
          type="primary"
          @click="() => handleStatus(2)"
        >
          通过
        </el-button>
        <el-button
          v-if="data.status < 3 && data.status > 0"
          type="primary"
          @click="() => handleStatus(3)"
        >
          驳回
        </el-button>
        <el-button
          v-if="data.status < 3"
          type="primary"
          @click="() => handleStatus(4)"
        >
          撤销
        </el-button>

        <el-button v-if="isWxWork && isMobile" type="primary" @click="shareWx">
          分享信息
        </el-button>
        <el-button v-if="isWxWork" type="primary" @click="chatToUsers">
          发起讨论
        </el-button>
        <el-button type="primary" @click="print">打印</el-button>
      </div>
    </div>
  </div>
</template>

<script>
  import router from '@/router'
  import { getOne, doStatus } from '@/api/dksb'
  import { ArrowLeft } from '@element-plus/icons-vue'
  import { useUserStore } from '@/store/modules/user'
  import {
    gradeOptions,
    claszOptions,
    coursetimeOptions,
    subjectOptions,
  } from '@/config'
  import { parseTime } from '@/utils'
  export default defineComponent({
    name: 'ManDetail',
    setup(props, { emit }) {
      const { proxy } = getCurrentInstance()
      const route = useRoute()
      const userStore = useUserStore()
      const { userId } = userStore

      console.log(proxy)
      console.log(userId)
      console.log(props, emit)

      const state = reactive({
        data: {
          id: '',
          corpId: '',
          reqUserid: '',
          comment: '',
          thirdNo: '',
          templateId: '',
          courses: [],
          status: 0, //0-未提交；1-审批中；2-已通过；3-已驳回；4-已取消
        },
      })

      const loadData = async () => {
        const { data } = await getOne(route.params.thirdNo).catch(() => {})
        state.data = data
      }

      onMounted(() => {
        loadData()
      })

      const getCourseDesc = (course) => {
        const { eventdate, grade, clasz, coursetime, subject } = course
        return `${getOptLabel(
          subjectOptions,
          subject
        )} ${eventdate} ${getOptLabel(
          coursetimeOptions,
          coursetime
        )} ${getOptLabel(gradeOptions, grade)} ${getOptLabel(
          claszOptions,
          clasz
        )} `
      }

      const getOptLabel = (options, value) => {
        let label = ''
        options.some((op) => {
          if (op.value === value) {
            label = op.label
            return true
          }
          if (op.children) {
            label = getOptLabel(op.children, value)
            if (label) return true
          }
        })
        return label
      }

      const goBack = () => {
        router.go(-1)
      }

      const handleStatus = async (status) => {
        const data = { status, thirdNos: [state.data.thirdNo] }
        await doStatus(data).catch(() => {})
        router.back()
      }

      const shareWx = () => {
        wx.invoke(
          'shareWechatMessage',
          {
            title: '代课申报详情', // 分享标题
            desc: '请点击进入代课申报查看详情', // 分享描述
            link: `http://wx.xerllent.cn/dksb#/detail/${state.data.thirdNo}`,
            imgUrl: 'http://wx.xerllent.cn/dksb/img/icons/dksb.png', // 分享封面
          },
          function (res) {
            if (res.err_msg == 'shareWechatMessage:ok') {
              console.log('share ok')
            }
          }
        )
      }

      const chatToUsers = () => {
        //1收集相关userIds
        const { reqUserid, auditUserid } = state.data
        let userIds = [userId]
        if (!userIds.includes(reqUserid)) {
          userIds.push(reqUserid)
        }
        if (auditUserid && !userIds.includes(auditUserid)) {
          userIds.push(auditUserid)
        }
        const courses = state.data.courses
        courses.forEach((course) => {
          if (!userIds.includes(course.srcUserid)) {
            userIds.push(course.srcUserid)
          }
          if (!userIds.includes(course.tarUserid)) {
            userIds.push(course.tarUserid)
          }
        })

        //2发起讨论
        wx.openEnterpriseChat({
          userIds: userIds.join(';'), //参与会话的企业成员列表
          groupName: '代课申报讨论组', // 会话名称。单聊时该参数传入空字符串""即可。
          chatId: state.chatId, // 若要打开已有会话，需指定此参数。如果是新建会话，chatId必须为空串
          success: function (res) {
            state.chatId = res.chatId //返回当前群聊ID，仅当使用agentConfig注入该接口权限时才返回chatId
            //3分享代课信息到讨论,注意：此功能只在聊天工具栏里点击该功能按钮磁能有效!!!!
            wx.invoke(
              'sendChatMessage',
              {
                msgtype: 'news', //消息类型，必填
                enterChat: true, //为true时表示发送完成之后顺便进入会话，仅移动端3.1.10及以上版本支持该字段
                news: {
                  link: `http://wx.xerllent.cn/dksb#/detail/${state.data.thirdNo}`,
                  title: '代课申报详情', //H5消息标题
                  desc: '请点击进入代课申报查看详情', //H5消息摘要
                  imgUrl: 'http://wx.xerllent.cn/dksb/img/icons/dksb.png', //H5消息封面图片URL
                },
              },
              function (res) {
                if (res.err_msg == 'sendChatMessage:ok') {
                  //发送成功
                }
              }
            )
          },
          fail: function (res) {
            if (res.errMsg.indexOf('function not exist') > -1) {
              alert('版本过低请升级')
            }
          },
        })
      }

      const isWxWork = /wxwork/i.test(navigator.userAgent)

      const isMobile = window.navigator.userAgent.match(
        /(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i
      ) // 是否手机

      const print = () => {
        router.push({ path: `/print/${state.data.thirdNo}` }).then(() => {})
      }

      return {
        ...toRefs(state),
        getCourseDesc,
        ArrowLeft,
        goBack,
        parseTime,
        handleStatus,
        shareWx,
        chatToUsers,
        isWxWork,
        isMobile,
        print,
      }
    },
  })
</script>

<style lang="scss" scoped>
  .index-container {
    .detailheader {
      height: 58px;
      line-height: 58px;
      border-bottom: 1px var(--el-border-color) var(--el-border-style);

      .sp_status {
        font-size: 10px;
        font-weight: 400;
        height: 16px;
        line-height: 16px;
        display: inline-block;
        margin: 2px 0 2px 5px;
        border-radius: 2px;
        color: var(--ww_base_white, #ffffff);
        text-align: center;
        padding: 0 3px;
        -webkit-text-size-adjust: none;
        -ms-text-size-adjust: none;
        text-size-adjust: none;
        background-color: var(--ww_accent_blue_lighten_1, #4b95f3);
        vertical-align: 0;
      }

      .sp_status_1 {
        background-color: var(--ww_accent_blue_lighten_1, #4b95f3);
      }

      .sp_status_2 {
        background-color: var(--ww_chrome_jade, #1ebd43);
      }

      .sp_status_3 {
        background-color: var(--ww_chrome_red_lighten_1, #f26a62);
      }

      .sp_status_0,
      .sp_status_4,
      .sp_status_6 {
        background-color: var(--ww_base_gray_010, #b5b8bb);
      }
    }
    .page__cont {
      max-width: 800px;
      margin: 0 auto;
      display: flex;
      flex-direction: column;
      padding: 20px;
      margin-top: 20px;
      .row1 {
        width: 100%;
        display: inline-flex;
        flex-direction: row;
        line-height: 32px;
        .label {
          display: inline-flex;
          color: darkgrey;
          font-family: serif;
          font-size: 16px;
          width: 80px;
          justify-content: flex-end;
          word-wrap: none;
          word-break: keep-all;
        }
        .description {
          color: var(--el-text-color-primary);
          font-family: serif;
          font-size: 16px;
        }
      }
      .rowx {
        width: 100%;
        display: inline-flex;
        flex-direction: row;
        flex-wrap: wrap;
        justify-content: center;
        margin-top: 20px;
      }
    }
  }
</style>
